package cn.car.service.impl;

import cn.car.domains.entity.VehicleCommonInfoEntity;
import cn.car.exception.CarAccessControlException;
import cn.car.mapper.VehicleCommonInfoMapper;
import cn.car.service.VehicleCommonInfoService;
import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 车辆信息服务实现类
 */
@Service
public class VehicleCommonInfoServiceImpl implements VehicleCommonInfoService {

    @Resource
    private VehicleCommonInfoMapper vehicleCommonInfoMapper;

    /**
     * 新增车辆信息
     * 自动填充创建时间，添加事务支持
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insert(VehicleCommonInfoEntity vehicle) {
        int rows;
        try {
            // 可在此处添加创建时间自动填充逻辑
            rows = vehicleCommonInfoMapper.insertVehicle(vehicle);
        } catch (DuplicateKeyException e) {
            throw CarAccessControlException.DATE_EXIST;
        }

        if (rows != 1) {
            throw CarAccessControlException.INSERT_ERROR.newInstance("插入普通车辆失败");
        }
        return vehicle.getId();
    }

    /**
     * 根据id查询车辆信息
     */
    @Override
    public VehicleCommonInfoEntity getVehicleById(Long id) {
        if (id == null) {
            return null;
        }
        return vehicleCommonInfoMapper.selectById(id);
    }

    /**
     * 根据车牌号查询车辆信息
     */
    @Override
    public VehicleCommonInfoEntity getVehicleByNumber(String vehicleNumber) {
        if (StrUtil.isEmpty(vehicleNumber)) {
            return null;
        }
        return vehicleCommonInfoMapper.selectByVehicleNumber(vehicleNumber);
    }

    /**
     * 更新车辆信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateVehicle(VehicleCommonInfoEntity vehicle) {
        // 校验ID是否存在
        if (vehicle.getId() == null) {
            throw CarAccessControlException.PARAMS_ERROR.newInstance("更新id不能为空");
        }

        // 执行更新操作
        int rows = vehicleCommonInfoMapper.updateById(vehicle);

        if (rows != 1) {
            throw CarAccessControlException.UPDATE_NOT_EXIST;
        }
    }

    /**
     * 根据ID删除车辆信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteVehicle(Long id) {
        // 校验ID是否存在
        if (id == null) {
            throw CarAccessControlException.PARAMS_ERROR.newInstance("删除id不能为空");
        }

        // 执行删除操作
        int rows = vehicleCommonInfoMapper.deleteById(id);

        if (rows != 1) {
            throw CarAccessControlException.DELETE_NOT_EXIST;
        }
    }

    @Override
    public VehicleCommonInfoEntity getVehicleByAssociationId(Long id) {
        return vehicleCommonInfoMapper.getVehicleByAssociationId(id);
    }
}
